package com.maikang.exammall.interceptor;

import com.maikang.exammall.entity.User;
import com.maikang.exammall.entity.UserContext;
import com.maikang.exammall.entity.constant.TokenConstant;
import com.maikang.exammall.exception.BadRequestException;
import com.maikang.exammall.exception.UnauthorizedException;
import com.maikang.exammall.repository.UserRepository;
import com.maikang.exammall.service.RedisService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@AllArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
    private final RedisService redisService;
    private final UserRepository userRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            throw new BadRequestException("缺少请求请求头token");
        }


        if (token.startsWith(TokenConstant.maTokenPrefix)) {
            String tokenUserIdKey = TokenConstant.getMaToken_userIdKeyFromToken(token);
            Object userId = redisService.get(tokenUserIdKey);
            if (userId == null) {
                throw new UnauthorizedException();
            }
            User user = userRepository.findById((Long) userId).get();
            UserContext.setUser(user);
            return true;
        }


        final String tokenUserInfoKey = TokenConstant.getToken_userInfoKeyFromToken(token);

        Object user = redisService.get(tokenUserInfoKey);
        if (user == null) {
            // TODO hard code for testing, need to remove.
            if (token.equals("token")) {
                User u= userRepository.findById(1L).get();
                if (!u.isTest()) throw new UnauthorizedException();
                UserContext.setUser(u);
                return true;
            }
            throw new UnauthorizedException();
        }
        UserContext.setUser((User) user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserContext.remove();
    }


}
